'use strict'
let pushMsg = require('../nodeapp/pushMsg')
let attackHandle = require('../core/attackHandle')
let createMonsterHandle = require('../core/createMonsterHandle')
let playerSessionMgr = require('../core/playerSessionMgr')
let mailDao = require('../dao/mailDao')
let templateConfig = require('../../config/templateConfig')
let totalConfig = templateConfig.totalConfig
let schedule = require('node-schedule')
let arenaDao = require('../dao/arenaDao')

//竞技场
class ArenaComponent {
  constructor() {
    this.players = new Map() //玩家id - >[玩家属性信息, 排名, 对战信息, 对战基本信息]
    this.playersArray = [] //玩家id
    let self = this
    arenaDao.getArena(function(res) {
      if (res && res.players.length > 0) {
        self.playersArray = res.playersArray
        let players = res.players
        for (let i = 0; i < players.length; i++) {
          let player = players[i]
          player[1].getAllFightAttriCopy = function() {
            let fightAttri = new FightAttri(this.fightAttri)
            fightAttri.hp = fightAttri.maxHp
            return fightAttri
          }
          self.players.set(player[0], [player[1], player[2], player[3], player[4]])
        }
      }
    })
  }

  join(player) {
    if (this.players.has(player._id)) {
      return -1
    }

    let arena1 = []
    let arena2 = []
    let index = this.playersArray.length
    this.playersArray.push(player._id)
    this.players.set(player._id, [player.getPlayerCopy(), index, arena1, arena2])
  }

  getArenaInfo(player) {
    this.join(player)
    let rankIndex = this.players.get(player._id)[1]
    let startIndex = rankIndex - 5
    if (startIndex <= 0) {
      startIndex = 0
    }
    let endIndex = rankIndex + 5
    if (endIndex >= this.playersArray.length) {
      endIndex = this.playersArray.length - 1
    }
    let info = []
    for (let i = startIndex; i <= endIndex; i++) {
      let pid = this.playersArray[i]
      let name = this.players.get(pid)[0].name
      info.push([i, name])
    }
    return info
  }

  getMyInfo(player) {
    this.join(player)
    let info = this.players.get(player._id)
    return [info[1], info[3]]
  }

  challengePlayer(player, index) {
    let pId = this.playersArray[index]
    if (!pId) {
      return -1
    }
    let playerInfo1 = this.players.get(player._id)
    let rankIndex = playerInfo1[1]
    if (rankIndex === index) {
      return -1
    }

    if (!(index >= rankIndex - 5 && index <= rankIndex + 5)) {
      return -1
    }

    //先判断被挑战的玩家是否在线
    let p = playerSessionMgr.getPlayer(pId)
    if (p) {
      p = p.getPlayerCopy()
    } else {
      p = this.players.get(pId)[0]
    }
    let fightMsg = attackHandle.playerBattle(player, p)
    let info = {
      p1: player.name,
      p2: p.name,
      result: fightMsg.result
    }

    if (playerInfo1[2].length > 15) {
      playerInfo1[2].shift()
    }
    playerInfo1[2].push(fightMsg)
    playerInfo1[3].push(info)

    let playerInfo2 = this.players.get(pId)
    if (playerInfo2[2].length > 15) {
      playerInfo2[2].shift()
    }
    playerInfo2[2].push(fightMsg)
    playerInfo2[3].push(info)

    //通知玩家
    pushMsg.arenaChallenge(pId, info)
    Log(p)
      //每次挑战获得的经验和金钱
    let config = templateConfig.total[290035][p.fightAttri.lvl]
    if (fightMsg.result === 1) {
      if (rankIndex > index) {
        playerInfo1[1] = index
        playerInfo2[1] = rankIndex
        let tmp = this.playersArray[rankIndex]
        this.playersArray[rankIndex] = this.playersArray[index]
        this.playersArray[index] = tmp
      }
      fightMsg.exp = config.getExp
      fightMsg.money = parseInt(config.getMoney * (1 + player.basicInfo.moneyBuff))
    } else {
      fightMsg.exp = parseInt(config.getExp / 2)
      fightMsg.money = parseInt(config.getMoney / 2 * player.basicInfo.moneyBuff)
    }
    player.basicInfo.money += fightMsg.money
    player.lvlup(fightMsg.exp)
    return fightMsg
  }

  //奖励发放
  reward() {
    Log('竞技场排名奖励发放')
    let playersArray = this.playersArray
    let length = playersArray.length
    let title = '竞技场奖励'
    let content = '竞技场奖励'
    if (length < 200) {
      for (let i = 0; i < length; i++) {
        let items = []
        let itemName = ''
        if (i <= 10) {
          items.push([240068, 1, 0])
          itemName = '王者竞技礼包'
        } else if (i <= 25) {
          items.push([240067, 1, 0])
          itemName = '炽热竞技礼包'
        } else if (i <= 50) {
          items.push([240066, 1, 0])
          itemName = '卓越竞技礼包'
        } else {
          items.push([240065, 1, 0])
          itemName = '耀眼竞技礼包'
        }
        let sendContent = content + ':' + itemName + ' 你的排名' + (i + 1)
        mailDao.newAndSave(playersArray[i], title, sendContent, items, 0, 0, function(err) {
          pushMsg.newMail(playersArray[i], '竞技场排名奖励,你获得了' + itemName + ',奖励请到邮箱查看')
        })
      }
    } else {
      for (let i = 0; i < length; i++) {
        let items = []
        let itemName = ''
        if (i <= Math.floor(length * 0.1)) {
          items.push([240068, 1, 0])
          itemName = '王者竞技礼包'
        } else if (i <= Math.floor(length * 0.3)) {
          items.push([240067, 1, 0])
          itemName = '炽热竞技礼包'
        } else if (i <= Math.floor(length * 0.6)) {
          items.push([240066, 1, 0])
          itemName = '卓越竞技礼包'
        } else {
          items.push([240065, 1, 0])
          itemName = '耀眼竞技礼包'
        }
        let sendContent = content + ':' + itemName + ' 你的排名' + (i + 1)
        mailDao.newAndSave(playersArray[i], title, sendContent, items, 0, 0, function(err) {
          pushMsg.newMail(playersArray[i], '竞技场排名奖励,你获得了' + itemName + ',奖励请到邮箱查看')
        })
      }
    }
  }

  saveArena(){
    let self = this
    if (this.playersArray.length > 0) {
      let players = this.players

      let infos = []
      for (let i of players.entries()) {
        let value = i[1]
        let key = i[0]
        let info = [key].concat(value)
        infos.push(info)
      }
      arenaDao.saveArena({
        playersArray: self.playersArray,
        players: infos
      }, function(err, ret) {})
    }
  }
}

let arenaComponent = new ArenaComponent()
module.exports = arenaComponent

let rule = new schedule.RecurrenceRule()
rule.hour = 21
rule.minute = 0
let j = schedule.scheduleJob(rule, function() {
  arenaComponent.reward()
})


//每隔5分钟保存一次竞技场信息
setInterval(function() {
  arenaComponent.saveArena()
}, 300000)



//角色战斗属性
class FightAttri {
  constructor(opts) {
    this.hp = opts.hp || 0 //生命
    this.maxHp = opts.maxHp || 0 //最大生命
    this.attack = opts.attack || 0 //攻击力
    this.defend = opts.defend || 0 //防御
    this.critRate = opts.critRate || 0 //暴击概率
    this.critHurt = opts.critHurt || 0 //暴击伤害
    this.skillRate = opts.skillRate || 0 //技能释放率
    this.skillHurtPer = opts.skillHurtPer || 0 //技能伤害率
    this.ignoreDefend = opts.ignoreDefend || 0 //无视防御力
    this.str = opts.str || 0 //力量:提升基础攻击力和少量生命
    this.con = opts.con || 0 //体质:提升防御和生命
    this.agile = opts.agile || 0 //意志:提升物理技能伤害
    this.wisdom = opts.wisdom || 0 //智慧:提升幸运和少量生命
    this.lucky = opts.lucky || 0 //幸运
    this.skills = opts.skills || []
    this.attackSkill = opts.attackSkill || [] //攻击触发技能
    this.defendSkill = opts.defendSkill || [] //防御触发技能
    this.buff = 0 //0初始状态
    this.debuff = 0 //0初始状态 1 眩晕
    this.lvl = opts.lvl || 1 //等级
    this.maxStamina = opts.maxStamina || 0 //最大体力
    this.money = opts.money || 0 //银币掉率
  }
}
